<template>
  <basic-container style="height: 100%">
    <el-container style="height: 100%">
      <!-- 搜索页 -->
      <el-main style="height: 100%;margin-left: 3px;">
        <el-row>
          <el-link :type="tabMode ? 'primary' : 'default'" :underline="false" style="font-size: 17px;font-weight: 600" @click="tabMode = true">知识搜索</el-link>
          <el-divider direction="vertical" />
          <el-link :type="!tabMode ? 'primary' : 'default'" :underline="false" style="font-size: 17px;font-weight: bolder" @click="tabMode = false">知识浏览</el-link>
        </el-row>
        <template v-if="tabMode">
          <el-row style="margin-top:10px;">
            <el-col :span="20">
              <el-autocomplete
                v-model="keyWord"
                class="inline-input"
                :fetch-suggestions="querySearch"
                debounce="1000"
                placeholder="请输入内容"
                size="medium"
                style="width:100%;margin-right: 10px;"
                @select="handleSelect"
                @keyup.enter.native="goSearch"
              />
            </el-col>
            <el-col :span="4" style="text-align: right;">
              <el-button type="primary" size="medium" style="width: 90%" @click="goSearch">搜索</el-button>
            </el-col>
          </el-row>
          <el-row style="margin-top: 10px;width: 99.5%">
            <el-tabs v-model="activeName" @tab-click="clickTabs">
              <el-tab-pane label="全部" name="all" />
              <el-tab-pane v-for="c in categoryList" :key="c.id" :label="c.name" :name="'name_'+c.id" />
            </el-tabs>
          </el-row>
          <el-row v-for="(s,index) in searchData" :style="index == searchData.length -1 ? 'margin-top: 9px;' : 'margin-top: 9px;margin-bottom: 9px;'">
            <el-col :span="24" :style="index == searchData.length -1 ? 'margin-bottom:0px;' : ''">
              <el-card shadow="never" style="background-color: rgb(245, 245, 245);cursor: pointer" @click.native="toDetail(s)">
                <div style="display: flex;height: 150px;">
                  <div v-if="s.type == 1" style="height: 150px;width: 150px;">
                    <img onerror="this.src='/img/default.jpeg'" :src="uploadUrl + '/blade-user/file/down?f=' + s.coverImg" style="height: 150px;width: 150px;border-radius: 5px;">
                  </div>
                  <div style="margin-left: 20px;">
                    <div>
                      <span class="title_span">{{ s.title }}</span>
                    </div>
                    <div style="margin-top: 3px;">
                      <span class="time_span" style="width: 180px;">时间：{{ s.updateTime }}</span>
                      <span class="time_span" style="margin-left: 80px;">浏览：{{ s.clickCountIn + s.clickCountOut }}次</span>
                    </div>
                    <div style="margin-top: 7px">
                      <span class="content_span">{{ s.aiSummary }}</span>
                    </div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
          <!-- 相关搜索 -->
          <el-row v-if="isSuggest" style="margin-top: 13px;margin-bottom: 9px;">
            <el-col :span="24">
              <el-card shadow="never" style="background-color: rgb(245, 245, 245);" @click.native="toDetail(s)">
                <div style="height: 120px;">
                  <!--                <div style="height: 150px;width: 150px;" v-if="s.type == 1">-->
                  <!--                  <img onerror="this.src='/img/default.jpeg'" :src="uploadUrl + '/blade-user/file/down?f=' + s.coverImg" style="height: 150px;width: 150px;border-radius: 5px;">-->
                  <!--                </div>-->
                  <div style="margin-left: 5px;height: 100%">
                    <div>
                      <span class="title_span" style="font-size: 15px;font-weight: 400;">相关搜索</span>
                    </div>
                    <div style="margin-top: 8px;display: flex;flex-wrap: wrap;width: 100%;align-content: space-evenly;height: 90%;">
                      <p v-for="(s,index) in suggestList" v-if="index < 8" class="time_span" style="color: rgb(64, 158, 255);margin-right:15px; " @click="handleSelect(s)">{{ s.value }}</p>
                    </div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
          <el-row style="text-align: right;">
            <el-pagination
              :current-page="current1"
              :page-sizes="[10, 200, 300, 400]"
              :page-size="size1"
              layout="prev, pager, next, sizes,jumper"
              :total="total1"
              @size-change="handleSizeChange1"
              @current-change="handleCurrentChange1"
            />
          </el-row>
        </template>
        <template v-if="!tabMode">
          <el-row style="margin-top: 10px;">
            <el-col :span="1">
              <el-popover
                v-model="categoryPopover"
                placement="bottom"
                width="400"
                trigger="click"
              >
                <el-tree
                  ref="leftTree"
                  class="custom_tree"
                  :data="data"
                  node-key="id"
                  default-expand-all
                  :expand-on-click-node="false"
                  @current-change="changeData"
                >
                  <span slot-scope="{ node, data }" class="custom-tree-node" style="padding: 5px">
                    <span style="width: 175px;overflow-x: auto">{{ node.label }}</span>
                  </span>
                </el-tree>
                <i slot="reference" class="el-icon-s-operation" style="font-size: 35px;font-weight: 600;cursor: pointer;" />
              </el-popover>
            </el-col>
            <el-col :span="23">
              <el-autocomplete
                v-model="tableKeyWord"
                class="inline-input"
                :fetch-suggestions="querySearch1"
                debounce="1000"
                placeholder="请输入内容"
                size="medium"
                style="margin-right: 10px;width: 80%"
              />
              <!--            <el-input  v-model="tableKeyWord" placeholder="请输入..." style="width: 60%;margin-right: 10px;" size="medium"></el-input>-->
              <el-button type="primary" size="medium" style="width: 8%" @click="tableSearch(false)">智能搜索</el-button>
              <el-button type="primary" size="medium" style="width: 8%" @click="tableSearch(true)">搜索</el-button>
            </el-col>
            <!--            <el-col :span="3" style="text-align: right;">-->
            <!--              -->
            <!--            </el-col>-->
          </el-row>
          <el-row>
            <el-table
              :data="tableData"
              :header-row-style="{background:'#f5f5f5',color:'#666'}"
              :header-cell-style="{background:'#f5f5f5',color:'#666'}"
              style="width: 100%;margin-top: 10px;text-align: center"
            >
              <el-table-column
                prop="title"
                label="标题"
              >
                <template slot-scope="scope">
                  <span style="cursor: pointer" @click="toDetail(scope.row)">
                    <i v-if="scope.row.topStatus == 1" class="el-icon-star-on" style="color: #409EFF;font-size: 15px;" />
                    {{ scope.row.title }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                prop="updateTime"
                label="更新日期"
                width="200"
              />
            </el-table>
          </el-row>
          <el-row style="text-align: right;margin-top: 10px;margin-bottom: 15px;">
            <el-pagination
              :current-page="current"
              :page-sizes="[10, 100, 200, 300, 400]"
              :page-size="size"
              layout="prev, pager, next, sizes,jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-row>
        </template>
      </el-main>
    </el-container>
  </basic-container>
</template>

<script>
//    import {articleList,aiSearch,suggest,list} from "@/api/system/knowledge";
//    import {getUserInfoByToken,getButtons} from '@/api/user'
//    import {mapGetters} from "vuex";
//    import {setToken} from '@/util/auth'
//    import {setStore, getStore} from '@/util/store'
export default {
  name: 'Index',
  data() {
    return {
      tabMode: true, // 顶部切换，true为搜索，false为浏览
      articleType: '1',
      activeName: 'all',
      data: [],
      tableData: [],
      knowledgeCategoryId: null,
      searchData: [],
      uploadUrl: '',
      keyWord: '',
      hotData: [],
      total1: 0,
      current1: 1,
      size1: 10,
      total: 0,
      current: 1,
      size: 10,
      tableKeyWord: '',
      searchType: null,
      queryData: [],
      queryData1: [],
      operationStatus: false,
      suggestList: [],
      isSuggest: false,
      suggestId: null,
      timeCheck: null,
      iframeStatus: getStore({ name: 'iframeStatus' }),
      generalSearch: false,
      currListLength: 0,
      queryDataInit: [],
      queryDataInit1: [],
      categoryList: [],
      categoryIds: null,
      tableKnowledgeCategoryId: null,
      categoryPopover: false,
      generalSearch: false,
      searchParentId: null
    }
  },
  computed: {
    ...mapGetters(['permission', 'website'])
  },
  mounted() {
    this.search()
    this.initQueryData()
    this.initQueryData1()
    this.initCategory()
    this.initTableData()
    this.uploadUrl = mainBaseUrl
  },
  created() {
    var that = this
    var token = this.$route.query.token
    if (token) {
      setToken(token)
      getUserInfoByToken({ token: token }).then(res => {
        that.$store.commit('SET_TOKEN', token)
        that.$store.commit('SET_TENANT_ID', res.data.data.tenant_id)
        that.$store.commit('SET_USER_INFO', res.data.data)
        that.iframeStatus = res.data.data.iframeStatus
        setStore({ name: 'iframeStatus', content: res.data.data.iframeStatus, type: 'session' })
        getButtons().then(res => {
          const data = res.data.data
          that.$store.commit('SET_PERMISSION', data)
        })
      })
    }
  },
  activated() {
    this.initTableData()
  },
  methods: {
    tableSearch(generalSearch) {
      this.current = 1
      this.generalSearch = generalSearch
      this.initTableData()
    },
    changeData(data, node) {
      this.current = 1
      this.tableKnowledgeCategoryId = data.id
      this.categoryPopover = false
      this.searchParentId = data.parentId == 0 ? data.id : data.parentId
      this.initQueryData1()
      this.initTableData()
    },
    resetKnowledge() {
      this.knowledgeCategoryId = null
    },
    handleCurrentChange(page) {
      this.current = page
      this.initTableData()
    },
    handleSizeChange(size) {
      this.size = size
      this.current = 1
      this.initTableData()
    },
    handleCurrentChange1(page) {
      this.current1 = page
      this.search()
    },
    handleSizeChange1(size) {
      this.size1 = size
      this.current1 = 1
      this.search()
    },
    clickTabs(tab) {
      var categoryId = tab.name.replace('name_', '')
      this.activeName = tab.name
      if (tab.name == 'all') {
        this.knowledgeCategoryId = null
        this.categoryIds = null
      } else {
        this.knowledgeCategoryId = categoryId
        this.categoryIds = categoryId
      }
      this.current1 = 1
      this.search()
    },
    toDetail(s) {
      var path = ''
      if (this.iframeStatus) {
        path = '/iframeArticleDetail'
      } else {
        path = '/knowledge/articleDetail'
      }
      this.$router.push({
        // name: '文章详情',
        path: path,
        query: {
          id: s.id
        }
      })
    },
    goSearch() {
      this.isSuggest = false
      this.suggestId = null
      this.timeCheck = 1
      this.generalSearch = false
      this.search()
    },
    initTableData() {
      var that = this
      var data = {
        current: that.current,
        size: that.size,
        title: that.tableKeyWord,
        timeCheck: 1,
        knowledgeCategoryId: that.tableKnowledgeCategoryId,
        categoryIds: that.searchParentId,
        parentId: that.searchParentId
      }
      if (that.generalSearch) {
        // 普通搜索
        data.generalSearch = '1'
      }
      articleList(data).then(res => {
        that.tableData = res.data.data.records
        that.total = res.data.data.total
      })
    },
    search() {
      // 搜索
      var that = this
      var data = {
        current: that.current1,
        size: that.size1,
        title: that.keyWord,
        type: that.searchType,
        id: that.suggestId,
        timeCheck: 1,
        knowledgeCategoryId: that.knowledgeCategoryId,
        categoryIds: that.categoryIds
      }
      if (that.suggestId) {
        data.title = null
      }
      articleList(data).then(res => {
        that.searchData = res.data.data.records
        that.total1 = res.data.data.total
        if (that.searchData.length > 0 && that.suggestId) {
          // 调用推荐接口
          suggest(data).then(res => {
            that.suggestList = res.data.data
          })
        } else {
          that.suggestList = []
        }
      })
    },
    // 搜索建议
    initQueryData() {
      var that = this
      var data = {
        current: 1,
        size: 10,
        // knowledgeCategoryId:1//热门问题
        categoryName: that.website.remenCategory,
        timeCheck: 1// 有效期ta
      }
      articleList(data).then(res => {
        that.queryData = []
        for (var i in res.data.data.records) {
          that.queryData.push({ value: res.data.data.records[i].title, id: res.data.data.records[i].id })
          that.queryDataInit.push({ value: res.data.data.records[i].title, id: res.data.data.records[i].id })
        }
      })
    },
    initQueryData1() {
      var that = this
      var data = {
        current: 1,
        size: 10,
        // knowledgeCategoryId:1//热门问题
        parentId: that.searchParentId,
        categoryName: that.website.remenCategory,
        timeCheck: 1// 有效期ta
      }
      articleList(data).then(res => {
        that.queryData1 = []
        for (var i in res.data.data.records) {
          that.queryData1.push({ value: res.data.data.records[i].title, id: res.data.data.records[i].id })
          that.queryDataInit1.push({ value: res.data.data.records[i].title, id: res.data.data.records[i].id })
        }
      })
    },
    // 搜索建议初始化,10个热门问题
    querySearch(queryString, cb) {
      var that = this
      if (queryString) {
        // 调用ai接口查询
        aiSearch({ keyword: queryString, count: 10 }).then(res => {
          cb(res.data.data)
        })
      } else {
        cb(this.queryData)
      }
    },
    querySearch1(queryString, cb) {
      var that = this
      if (queryString) {
        // 调用ai接口查询
        aiSearch({ keyword: queryString, count: 10 }).then(res => {
          cb(res.data.data)
        })
      } else {
        cb(this.queryData1)
      }
    },
    handleSelect(item) {
      // 用id查询
      // this.keyWord = item.value;
      // this.search();
      this.isSearch = true
      this.suggestId = item.id
      this.keyWord = item.value
      this.isSuggest = true
      this.search()
    },
    initCategory() {
      var that = this
      list({}).then(res => {
        var data = res.data.data
        that.data = that.getTrees(data, 0)
        for (var i = 0; i < res.data.data.length; i++) {
          if (data[i].name == '外部知识库' || data[i].name == '内部知识库' || data[i].name == '问答库') {
            that.categoryList.push(data[i])
          }
        }
        that.$nextTick(() => {
          that.changeData(that.data[0], null)
          // that.$refs.leftTree.setCurrentKey(that.data[0].id);
          // that.initQueryData();
          that.initQueryData1()
        })
      })
    },
    getTrees(list, parentId) {
      const items = {}
      // 获取每个节点的直属子节点，*记住是直属，不是所有子节点
      for (let i = 0; i < list.length; i++) {
        list[i].label = list[i].name
        const key = list[i].parentId
        if (items[key]) {
          items[key].push(list[i])
        } else {
          items[key] = []
          items[key].push(list[i])
        }
      }
      return this.formatTree(items, parentId)
    },
    formatTree(items, parentId) {
      const result = []
      if (!items[parentId]) {
        return result
      }
      for (const t of items[parentId]) {
        t.children = this.formatTree(items, t.id)
        result.push(t)
      }
      return result
    }
  }
}
</script>

<style lang="less" scoped>
  /deep/ .el-card{
    height: 100% !important;
  }
  /*/deep/ .el-tabs__item{*/
  /*  width: 100px;*/
  /*  text-align: center;*/
  /*  font-size: 16px;*/
  /*}*/

  .title_span{
    white-space: nowrap;
    text-align: left;
    font-size: 16px;
    font-weight: 700;
    font-style: normal;
    text-decoration: none;
    font-family: 'Microsoft YaHei';
    color: rgb(51, 51, 51);
  }

  .time_span{
    white-space: nowrap;
    text-align: left;
    font-size: 14px;
    font-weight: 400;
    font-style: normal;
    text-decoration: none;
    font-family: 'Microsoft YaHei';
    color: rgb(153, 153, 153);
    cursor: pointer;
  }

  .content_span{
    font-size: 14px;
    font-weight: 400;
    font-style: normal;
    text-decoration: none;
    font-family: 'Microsoft YaHei';
    color: rgb(51, 51, 51);
  }

  /deep/ .el-divider--horizontal{
    margin: 4px 0;
  }

  /deep/ .el-dialog__body{
    padding-top: 0px !important;
   }

  .el-select-dropdown__item{
    background-color: #0000 !important;
  }

  .el-select-dropdown__item:hover{
    background-color: #0000 !important;
  }

  .el-select-dropdown__item.selected{
    font-weight: normal;
  }

  /deep/ .el-card__body{
    height: 100% !important;
  }

</style>
